package com.katze.common.data.converters;

import com.katze.common.DatePattern;

import java.util.Date;

public class DateConverter implements Converter<Date> {

    @Override
    public Date format(Object o) {
        if (o == null) {
            return null;
        } else if (o instanceof String){
            try {
                if (((String) o).contains(".")) {
                    return DatePattern.NORM_DATETIME_MS_FORMAT.parse((String) o);
                } else {
                    return DatePattern.NORM_DATETIME_FORMAT.parse((String) o);
                }
            } catch (Exception e) {
                throw new RuntimeException("日期转换失败, 值为[" + o + "]");
            }
        } else if (o instanceof Long){
            try {
                return new Date((Long) o);
            } catch (Exception e) {
                throw new RuntimeException("日期转换失败, 值为[" + o + "]");
            }
        } else if (o instanceof Date){
            try {
                return (Date) o;
            } catch (Exception e) {
                throw new RuntimeException("日期转换失败, 值为[" + o + "]");
            }
        } else {
            throw new RuntimeException(o.getClass() + "不能转换为 java.util.Date, 值为[" + o + "]");
        }
    }

}
